package com.kly.cashmall.widget.picker;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build.VERSION;

import androidx.fragment.app.Fragment;

import com.kly.cashmall.R;
import com.kly.cashmall.utils.function.ToastUtil;

/**
 * @author
 */
public class PhotoPicker {
    private static final int REQUEST_CODE_PICK_CAMERA = 33;
    private static final int REQUEST_CODE_PICK_GALLERY = 34;
    private Object obj;
    private TakeListener takeListener;
    private Uri mPictureUri;
    private int maxThumbKB = 1024;
    private int maxThumbSize = 307200;
    private int maxThumbLength = 3000;

    public static PhotoPicker create(Fragment fragment) {
        return new PhotoPicker(fragment);
    }

    public static PhotoPicker create(Activity activity) {
        return new PhotoPicker(activity);
    }

    private PhotoPicker(Object object) {
        this.obj = object;
    }

    private Activity getActivity() {
        if (this.obj instanceof Fragment) {
            return ((Fragment) this.obj).getActivity();
        } else {
            return this.obj instanceof Activity ? (Activity) this.obj : null;
        }
    }

    private void startActivityForResult(Intent intent, int requestCode) {
        Activity activity = this.getActivity();
        if (activity != null && !activity.isFinishing()) {
            if (intent.resolveActivity(activity.getPackageManager()) != null) {
                if (this.obj instanceof Fragment) {
                    ((Fragment) this.obj).startActivityForResult(intent, requestCode);
                    return;
                }

                if (this.obj instanceof Activity) {
                    ((Activity) this.obj).startActivityForResult(intent, requestCode);
                    return;
                }
            }

            ToastUtil.showToast(getActivity().getResources().getString(R.string.login_failed));
        }
    }

    @SuppressLint("WrongConstant")
    public void pickFromCamera() {
        Activity activity = this.getActivity();
        if (activity != null && !activity.isFinishing()) {
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            this.mPictureUri = PickFileUtil.getCameraUri(activity);
            if (this.mPictureUri == null) {
                ToastUtil.showToast(getActivity().getResources().getString(R.string.check_card));
            } else {
                intent.putExtra("output", this.mPictureUri);
                intent.putExtra("return-data", true);
                intent.putExtra("outputFormat", CompressFormat.JPEG.toString());
                activity.grantUriPermission(activity.getPackageName(), this.mPictureUri, 1);
                intent.addFlags(3);
                this.startActivityForResult(intent, 33);
            }
        }
    }

    public void setMaxThumbKB(int maxThumbKB) {
        this.maxThumbKB = maxThumbKB;
    }

    public void setMaxThumbSize(int maxThumbSize) {
        this.maxThumbSize = maxThumbSize;
    }

    public void setMaxThumbLength(int maxThumbLength) {
        this.maxThumbLength = maxThumbLength;
    }

    @SuppressLint("WrongConstant")
    public void pickFromGallery() {
        Activity activity = this.getActivity();
        if (activity != null && !activity.isFinishing()) {
            Intent intent;
            if (VERSION.SDK_INT >= 19) {
                Intent chooserIntent = new Intent();
                chooserIntent.setType("image/*");
                chooserIntent.setAction("android.intent.action.PICK");
                intent = Intent.createChooser(chooserIntent, "Select Picture");
                intent.putExtra("return-data", true);
            } else {
                intent = new Intent("android.intent.action.GET_CONTENT");
                intent.setType("image/*");
            }

            intent.addFlags(3);
            intent.putExtra("output", PickFileUtil.getGalleyTempUri(activity));
            intent.putExtra("outputFormat", CompressFormat.JPEG.toString());
            this.startActivityForResult(intent, 34);
        }
    }

    public void handleActivityResult(int requestCode, int resultCode, Intent data) {
        Activity activity = this.getActivity();
        if (activity != null && !activity.isFinishing()) {
            if (resultCode == -1) {
                String filePath;
                switch (requestCode) {
                    case REQUEST_CODE_PICK_CAMERA:
                        Uri uri = data == null ? null : data.getData();
                        filePath = ImagePickUtil.getPath(activity, uri == null ? this.mPictureUri : uri);
                        this.callTakeListener(filePath);
                        break;
                    case REQUEST_CODE_PICK_GALLERY:
                        filePath = ImagePickUtil.getPath(activity, data == null ? null : data.getData());
                        this.callTakeListener(filePath);
                }
            } else {
                switch (requestCode) {
                    case REQUEST_CODE_PICK_CAMERA:
                        if (this.takeListener != null) {
                            this.takeListener.onTakeFailure(getActivity().getResources().getString(R.string.pictures_failed));
                        }
                        break;
                    case REQUEST_CODE_PICK_GALLERY:
                        if (this.takeListener != null) {
                            this.takeListener.onTakeFailure(getActivity().getResources().getString(R.string.choose_picture_failure));
                        }
                }
            }

        }
    }

    private void callTakeListener(String filePath) {
        if (FileUtil.isFileExist(filePath)) {
            this.handleFile(filePath);
        } else {
            if (this.takeListener != null) {
                this.takeListener.onTakeFailure(getActivity().getResources().getString(R.string.not_find_pictures));
            }

        }
    }

    private void handleFile(final String path) {
        AsyncTask.execute(new Runnable() {
            public void run() {
                Context context = PhotoPicker.this.getActivity();
                if (context != null) {
                    if (PhotoPicker.this.maxThumbSize < 0) {
                        PhotoPicker.this.maxThumbSize = 0;
                    }

                    Bitmap bitmapPhoto = BitmapReader.readBitmap(path, PhotoPicker.this.maxThumbKB, PhotoPicker.this.maxThumbLength, PhotoPicker.this.maxThumbLength);
//                    Bitmap bitmapPhoto = BitmapReader.readBitmap(path, PhotoPicker.this.maxThumbKB, (int) Math.sqrt(PhotoPicker.this.maxThumbSize), (int) Math.sqrt(PhotoPicker.this.maxThumbSize));
//                    if (bitmapPhoto != null) {
//                        double bitmapSize = 1.0D * (double)bitmapPhoto.getWidth() * (double)bitmapPhoto.getHeight();
//                        if (bitmapSize > (double) PhotoPicker.this.maxThumbSize) {
//                            bitmapPhoto = BitmapUtil.scaleImage(bitmapPhoto, (float) Math.sqrt((double) PhotoPicker.this.maxThumbSize / bitmapSize));
//                        }
//                    }

                    String pictureDir = BitmapSaver.create().saveBitmap(PickFileUtil.getTempDir(context), "IMG" + System
                            .currentTimeMillis() + ".jpg", bitmapPhoto, PhotoPicker.this.maxThumbKB, true);
                    if (bitmapPhoto != null && !bitmapPhoto.isRecycled()) {
                        bitmapPhoto.recycle();
                    }

                    if (!FileUtil.isFileExist(pictureDir)) {
                        pictureDir = path;
                    }

                    String finalPictureDir = pictureDir;
                    RunnablePost.post(new Runnable() {
                        public void run() {
                            if (PhotoPicker.this.takeListener != null) {
                                if (FileUtil.isFileExist(finalPictureDir)) {
                                    PhotoPicker.this.takeListener.onTakeSuccess(finalPictureDir);
                                } else {
                                    PhotoPicker.this.takeListener.onTakeFailure(getActivity().getResources().getString(R.string.not_find_pictures));
                                }
                            }

                        }
                    });
                }
            }
        });
    }

    public void setTakeListener(TakeListener takeListener) {
        this.takeListener = takeListener;
    }

    public void release() {
        this.takeListener = null;
        this.mPictureUri = null;
    }
}